package com.opensource.component.query.configuration;

import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @author ZonLen since on 2021/10/8 下午12:55
 */
@Slf4j
@Configuration
public class MybatisPlusExtendConfiguration implements BeanPostProcessor {

  /**
   * 分页插件
   */
  @Bean
  @ConditionalOnProperty(name = "mybatis.plus.pagination.enable", havingValue = "true", matchIfMissing = true)
  public MybatisPlusInterceptor paginationInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    PaginationInnerInterceptor innerInterceptor = new PaginationInnerInterceptor();
    innerInterceptor.setMaxLimit(30000L);
    interceptor.addInnerInterceptor(innerInterceptor);
    return interceptor;
  }

  /**
   * @see DefaultSqlInjector SQL注入器
   */
  @Bean
  public ExtendSqlInjector extendSqlInjector() {
    return new ExtendSqlInjector();
  }


  /**
   * 启动对Mybatis plugin FILO分库分表插件优先执行
   */
  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof SqlSessionFactory) {
      SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) bean;
      sqlSessionFactory.getConfiguration().setObjectWrapperFactory(new MybatisMapWrapperFactory());
      sqlSessionFactory.getConfiguration().addInterceptor(new MybatisPlusShardingInterceptor());
    }
    return bean;
  }
}
